import { all } from "./all";
import { put } from "./put";
import { select } from "./select";
import { actionsMap, updateLoadingState } from "./store";
import { IDispatchParams } from "./types";
import { update } from "./update";

export function useDispatch() {
  return dispatch;
}

export async function dispatch<T = any>(params: IDispatchParams): Promise<T> {
  const { type } = params;
  updateLoadingState({ [type]: true });
  const [ns, fn] = type.split("/");
  const func = actionsMap[ns] ? actionsMap[ns][fn] : undefined;
  let ret: any;
  try {
    ret = func ? await func(params, { select, update, put, all }) : undefined;
  } finally {
    updateLoadingState({ [type]: false });
  }
  return ret;
}
